<?php

namespace app\api\model;

use think\Model;
use think\Db;

class Tenergy extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'ty_tenergy';
    /**
     * 获取
     */
    public static  function addInfo($param,$data,$new_TEnergy,$order)
    {
        Db::startTrans();
        try{
            $where1 = ['hr_id' => $param['h_id']];
            $lastInfo = Tenergy::getLastInfo($param);
            $data['change'] = $new_TEnergy - $lastInfo['TEnergy'];
            $res3 = HousingResources::updateStatistics($where1,$data['change']);
            $order['room_usage'] = $data['change'];
            $order['unit_price'] =  HousingResources::getUnitPrice($where1);
            $res = Db::table('ty_tenergy')->insert($data);
            $res2 = ElecOrder::addOrder($order);
            if($res && $res2 && $res3){
                Db::commit();
                ////日志
                $logContent = "\r\n";
                $logContent .= "Datetime: " . date("Y-m-d H:i:s") . ' time: ' . time() . "\r\n";
                $logContent .= "energy: " . json_encode($data) . "\r\n";
                $logContent .= "order: " . json_encode($order) . "\r\n";
                $logContent .= "Res: " . json_encode($res).'-'.json_encode($res2).'-'.json_encode($res3) . "\r\n";
                Tenergy::writeLog($logContent, "getTEnergy");
                return 'true';
            }
            Db::rollback();
        }catch (\Exception $e){
            Db::rollback();
            return $e->getMessage();
        }
    }
    public static  function getLastInfo($where)
    {
        $res = Db::table('ty_tenergy')
            ->order('t_id desc')
            ->where($where)
            ->find();
        return $res;
    }
    public static  function addInfoOnly($data)
    {
        $res =   Db::table('ty_tenergy')
            ->insert($data);
        return $res;
    }
}
